//
//  ViewController.swift
//  sandbox
//
//  Created by 杨岑 on 2018/7/25.
//  Copyright © 2018 杨岑. All rights reserved.
//

import Cocoa

class MainVC: NSViewController, NSTableViewDataSource, NSTableViewDelegate, NSTextDelegate {
    let HelpName = "Help"
    
    @IBOutlet weak var input: NSTextField!
    @IBOutlet var textView: NSTextView!
    @IBOutlet weak var busyIndicator: NSProgressIndicator!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.busyIndicator.startAnimation(self)
        //let appDelegate = NSApp.delegate as! AppDelegate

        func buildHelpRtf() {
            if let htmlFileURL = Bundle.main.url(forResource: "Help", withExtension: "html") {
                var html = try! String(contentsOf: htmlFileURL)
                html = html.replacingOccurrences(of: "{:title:}", with: "FAQ List")
                html = html.replacingOccurrences(of: "{:text color:}", with: "#ababff")
                
                var listText = String()
                for i in 1...10 {
                    let Q = NSLocalizedString("Q\(i)", tableName: HelpName, comment: "")
                    listText.append("<li><div><u>\(Q)</u></div>")
                    let A = NSLocalizedString("A\(i)", tableName: HelpName, comment: "")
                    listText.append("<div>\(A)</div></li>")
                    listText.append("\n")
                }
                html = html.replacingOccurrences(of: "{:list:}", with: listText)
                
                if let htmlData = html.data(using: .utf8) {
                    if let atstr = NSAttributedString(html: htmlData, documentAttributes: nil) {
                        let range = NSRange(location: 0, length: atstr.length)
                        atstr.enumerateAttributes(in: range, options: [], using: { (attrs, range, boolValue) in
                            //print("\(range) \(attrs)")
                        })
                        self.textView.textStorage?.setAttributedString(atstr)
                    }
                }
            }
        }
        
        buildHelpRtf()
    }

    private func createBookmark(from url: URL) throws -> Data? {
        return try url.bookmarkData(options: .withSecurityScope,
                                    includingResourceValuesForKeys: nil,
                                    relativeTo: nil)
    }
    
    // MARK: Event Handlers
    
    @IBAction func infoButton_click(_ sender: Any) {
        if let data = UserDefaults.standard.value(forKey: "bookmark") as? Data {
            print("Got \(data.count) bytes of bookmark data")
            do {
                var isStale = false
                let url = try URL(resolvingBookmarkData: data,
                              options: [.withSecurityScope, .withoutUI],
                              relativeTo: nil,
                              bookmarkDataIsStale: &isStale)
                print(url)
                if isStale {
                    print("stale bookmark")
                }
                let _ = url.startAccessingSecurityScopedResource()
                do {
                    let files = try FileManager.default.contentsOfDirectory(atPath: url.path)
                    print(files)
                } catch {
                    print(error)
                }
                url.stopAccessingSecurityScopedResource()
            } catch {
                print(error)
            }
        }
    }
    
    @IBAction func testButton_click(_ sender: Any) {
        print("\(sender)")
        //print(NSStringFromSelector(#selector(showHelp(_:))))
        
        func testDownloader() {
            let d = MyDownloader()
            d.startLoad("http://www.w3.org/")
        }
        
        func testToolbar() {
            if let toolbar = NSApp.mainWindow?.toolbar {
                for tbi in toolbar.items {
                    print("\(type(of: tbi)) \(tbi.itemIdentifier.rawValue) \(tbi.isEnabled)")
                }
            }
        }
        
        func testStoryboardWindow() {
            let storyboard = NSStoryboard(name: "Second", bundle: nil)
            if let wc = storyboard.instantiateInitialController() as? NSWindowController {
                wc.showWindow(self)
            }
        }
        
        func testOpenPanel() {
            let openPanel = NSOpenPanel()
            openPanel.canChooseDirectories = true
            openPanel.canChooseFiles = false
            openPanel.allowsMultipleSelection = false
            if openPanel.runModal() == .OK {
                print(openPanel.url!)
                do {
                    if let data = try self.createBookmark(from: openPanel.url!) {
                        print("Created URL bookmark of \(data.count) bytes")
                        UserDefaults.standard.set(data, forKey: "bookmark")
                    }
                } catch {
                    print(error)
                }
            }
        }
        
        //testOpenPanel()
        //testStoryboardWindow()
        let MAS = self.textView.textStorage!
        /*
        var index = 0
        while index < MAS.length {
            var range = NSRange(location: 0, length: 0)
            MAS.attribute(.foregroundColor, at: index, effectiveRange: &range)
            print(range.location, range.length)
            MAS.removeAttribute(.foregroundColor, range: range)
            MAS.addAttribute(.foregroundColor, value: NSColor.magenta, range: range)
            index = range.location + range.length
        }*/
        MAS.removeAttribute(.foregroundColor, range: NSMakeRange(0, MAS.length));
        MAS.addAttribute(.foregroundColor, value: NSColor.green, range: NSMakeRange(0, MAS.length))
    }
    
    @IBAction func textField_action(_ sender: Any) {
        print("textField_action")
    }
    
    // MARK: NSControlTextEditingDelegate
    
    func controlTextDidChange(_ notification: Notification) {
        if let t = notification.object as? NSTextField {
            print("\(t) text changed: \(t.stringValue)")
        }
    }
    
    @IBAction func menuItem_select(_ sender: Any) {
        let menuItem = sender as! NSMenuItem
        print("MainVC: menu selected: \(menuItem) \(menuItem.menu!.identifier!)")
        if let view = self.view.window?.firstResponder as? NSView {
            let addr = Unmanaged.passRetained(view).toOpaque()
            print("First Responder: \(type(of: view)) \(addr)")
        }
    }
    
    @IBAction func showHelp(_ sender: Any) {
        let alert = NSAlert()
        alert.window.title = "Custom Help"
        alert.messageText = "This is custom help."
        alert.informativeText = "Detailed help contents here..."
        alert.runModal()
    }
    
    
    // MARK: NSTextDelegate
    
    func textDidChange(_ notification: Notification) {
        if let t = notification.object as? NSTextView {
            print("textDidChange: \(t.identifier!.rawValue)")
        }
    }
    
    func textDidBeginEditing(_ notification: Notification) {
        if let t = notification.object as? NSTextView {
            print("textDidBeginEditing: \(t.identifier!.rawValue)")
        }
    }
    
    func textDidEndEditing(_ notification: Notification) {
        if let t = notification.object as? NSTextView {
            print("textDidEndEditing: \(t.identifier!.rawValue)")
        }
    }
}

